package com.example.controller;

/**
 * @author 吕一明
 * @公众号 码客在线
 *
*/

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.common.lang.Result;
import com.example.entity.User;
import com.example.entity.UserMessage;
import com.example.search.model.PostDocument;
import com.example.service.SearchService;
import com.example.vo.PostVo;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class IndexController extends BaseController {

    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";

    @Autowired
    private Producer producer;

    @Autowired
    SearchService searchService;

    @RequestMapping({"", "/", "/index"})
    public String index () {

        IPage results = postService.paging(getPage(), null, null, null, null, "created");
        req.setAttribute("pageData", results);
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "auth/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public Result doLogin(String email, String password) {

        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            return Result.fail("用户名或密码不能为空！");
        }
        AuthenticationToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));

        try {

            //尝试登陆，将会调用realm的认证方法
            SecurityUtils.getSubject().login(token);

        }catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在");
            } else if (e instanceof LockedAccountException) {
                return Result.fail("用户被禁用");
            } else if (e instanceof IncorrectCredentialsException) {
                return Result.fail("密码错误");
            } else {
                return Result.fail("用户认证失败");
            }
        }
        return Result.succ("登录成功", null, "/");
    }

    @GetMapping("/register")
    public String register() {
        return "auth/register";
    }

    @GetMapping("/capthca.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //把验证码存到shrio的session中
        SecurityUtils.getSubject().getSession().setAttribute(KAPTCHA_SESSION_KEY, text);

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
    }


    @ResponseBody
    @PostMapping("/register")
    public Result doRegister(User user, String captcha, String repass) {

        String kaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute(KAPTCHA_SESSION_KEY);
        if(!kaptcha.equalsIgnoreCase(captcha)) {
            return Result.fail("验证码不正确");
        }

        if(repass == null || !repass.equals(user.getPassword())) {
            return Result.fail("两次输入密码不一致");
        }

        Result result = userService.register(user);
        result.setAction("/login"); // 注册成功之后跳转的页面
        return result;
    }

    @GetMapping("/logout")
    public String logout() throws IOException {
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }

    @ResponseBody
    @PostMapping("/message/nums/")
    public Object messageNums() throws IOException {
        int count = userMessageService.count(new QueryWrapper<UserMessage>()
                .eq("to_user_id", getProfileId())
                .eq("status", 0)
        );
        return MapUtil.builder().put("status", 0).put("count", count).build();
    }

    @RequestMapping("/search")
    public String search(@RequestParam(defaultValue = "1") Integer current,
                         @RequestParam(defaultValue = "10")Integer size,
                         String q) {

        Pageable pageable = PageRequest.of(current - 1, size);
        Page<PostDocument> documents = searchService.query(pageable, q);

        IPage pageData = new com.baomidou.mybatisplus.extension.plugins.pagination.Page
                (current, size, documents.getTotalElements());
        pageData.setRecords(documents.getContent());

        req.setAttribute("pageData", pageData);
        req.setAttribute("q", q);
        return "search";
    }
}
